package com.ctbri.manage.process.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.ctbri.manage.process.model.GeneratorConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.jdbc.core.JdbcTemplate;*/

import java.io.*;
import java.util.*;

/**
 * @author qs
 */
public class DataProcessUtils {

    static final Logger logger = LoggerFactory.getLogger(DataProcessUtils.class);
    /**
     * @param path 配置文件路径
     * @return String
     * @Name getDynamicSqlByConfig
     * @Description 根据配置文件参数，动态获取SQL
     */
    public String getDynamicSqlByConfig(String path) {
        String sql = "";
        Properties properties = new Properties();
//        try {
//            properties.load(new InputStreamReader(new FileInputStream(path), "UTF-8"));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        /**1.获取配置参数**/
        //#基准表对应查询字段放入到数组中，例如：filedArr1=names,hobby
        String filed1 = properties.get("filedArr1").toString();
        String[] filedArr1 = filed1.split(",");

        //#目标表对应查询字段放入到数组中 例如：filedArr2=names,hobby
        String filed2 = properties.get("filedArr2").toString();
        String[] filedArr2 = filed2.split(",");

        GeneratorConfig generatorConfig = new GeneratorConfig(Integer.valueOf(properties.get("dataType").toString()),
                properties.get("templateCode").toString(),
                properties.get("tableName1").toString(),
                properties.get("tableName2").toString(), filedArr1, filedArr2,
                properties.get("province").toString());

        /**2.查询SQL模板**/
        List<Map<String, Object>> mdmTemplateList = selectSqlTemplate(generatorConfig);

        /**3.动态获取SQL**/
        if (mdmTemplateList.size() > 0) {
            sql = getTemplateSql(mdmTemplateList, generatorConfig);
        } else {
            sql = "未查询到符合条件的模板";
            logger.info("未查询到符合条件的模板");
        }
        return sql;
    }

    /**
     * @param generatorConfig
     * @return List<Map < String, Object>>
     * @Name selectSqlTemplate
     * @Description 根据配置文件参数，往数据库中查询SQL模板
     */
    public List<Map<String, Object>> selectSqlTemplate(GeneratorConfig generatorConfig) {
        //为安全性修改
        //JdbcTemplate jdbcTemplate = null;
        List<Map<String, Object>> mdmTemplateList = new ArrayList<Map<String, Object>>();
      /*  try {
            //连接数据库
            jdbcTemplate = DbOperationUtils.getJdbcTemplate();
            //拼接SQL
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT content AS content FROM mdm_template ");
            sql.append(" WHERE ");
            sql.append(" data_type=" + generatorConfig.getDataType());
            sql.append(" AND template_code='" + generatorConfig.getTemplateCode() + "'");
            sql.append(" AND isValid=0");

            // String sql = "SELECT content FROM mdm_template WHERE data_type=1 AND template_name='查询相同数' AND param_num=4 AND isValid=0 ";
            //查询SQL模板
            mdmTemplateList = jdbcTemplate.queryForList(sql.toString());
        } finally {
            ((DruidDataSource) jdbcTemplate.getDataSource()).close();
        }*/
        return mdmTemplateList;
    }

    /**
     * @param mdmTemplateList，generatorConfig
     * @return
     * @Name getTemplateSql
     * @Description 动态获取SQL
     */
    public String getTemplateSql(List<Map<String, Object>> mdmTemplateList, GeneratorConfig generatorConfig) {
        Map<String, Object> mdmTemplateMap = mdmTemplateList.get(0);
        String contentSql = mdmTemplateMap.get("content").toString();

        // 初始化并取得Velocity引擎
//        VelocityEngine ve = new VelocityEngine();
//        ve.init();
        // 取得velocity的模版内容, 模板内容来自数据库，如：
        // String content ="SELECT a.$field_a1,a.$field_a2 FROM $table_name1 AS a,$table_name2 AS b where a.$field_a1=b.$field_b1 and a.$field_a2 = b.$field_b2;"

        // 输出流
        StringWriter writer = new StringWriter();
        // 取得velocity的上下文context
//        VelocityContext context = new VelocityContext();
        // 把数据填入上下文
//        context.put("table_name1", generatorConfig.getTableName1()); //基准表
//        context.put("table_name2", generatorConfig.getTableName2()); //目标表
//        context.put("a_allElems", generatorConfig.getFiledArr1()); //基准表对应字段数组
//        context.put("b_allElems", generatorConfig.getFiledArr2()); //目标表对应字段数组
//        context.put("province", generatorConfig.getProvince()); //省份参数

        // 转换输出
        //为安全性修改
       // ve.evaluate(context, writer, "", contentSql); // 关键方法
        String resultSql = writer.toString();
        logger.info("生成SQL为："+resultSql);
        return resultSql;
    }

    /**
     * @param path 配置文件路径
     * @return String
     * @Name getDynamicSqlFromTempFile
     * @Description 根据配置文件参数，从文件中获取SQL模板，动态生成SQL模板
     */
    public String getDynamicSqlFromTempFile(String path) {
        String sql = "";
        Properties properties = new Properties();
//        try {
//            properties.load(new InputStreamReader(new FileInputStream(path), "UTF-8"));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        /**1.获取配置参数**/
        //#基准表对应查询字段放入到数组中，例如：filedArr1=names,hobby
        String filed1 = properties.get("filedArr1").toString();
        String[] filedArr1 = filed1.split(",");

        //#目标表对应查询字段放入到数组中 例如：filedArr2=names,hobby
        String filed2 = properties.get("filedArr2").toString();
        String[] filedArr2 = filed2.split(",");

        GeneratorConfig generatorConfig = new GeneratorConfig(Integer.valueOf(properties.get("dataType").toString()),
                properties.get("templateCode").toString(),
                properties.get("tableName1").toString(),
                properties.get("tableName2").toString(), filedArr1, filedArr2,
                properties.get("province").toString(),
                Integer.valueOf(properties.get("checkFlag").toString()));

        /**2.从文件中获取SQL模板**/
        List<Map<String, Object>> mdmTemplateList = new ArrayList<>();
        try {
            String templateName = generatorConfig.getDataType() + "-" + generatorConfig.getTemplateCode();
            if(generatorConfig.getCheckFlag() == 2){
                   templateName += "-"+ generatorConfig.getCheckFlag();
            }
            //InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/"+generatorConfig.getDataType() + "-" + generatorConfig.getTemplateCode() + ".sql");
//            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/"+ templateName + ".sql");
//            String content = printFileContent(in);
//            logger.info("读取模板内容："+content);
            //System.out.println("读取模板内容："+content);
            Map<String, Object> sqlMap = new HashMap<>();
//            sqlMap.put("content", content);
            mdmTemplateList.add(sqlMap);
        } catch (Exception e) {
            logger.error("未找到SQL文件模板或读取文件失败:"+e);
            throw new RuntimeException(e);
        }

        /**3.动态获取SQL**/
        if (mdmTemplateList.size() > 0) {
            sql = getTemplateSql(mdmTemplateList, generatorConfig);
        } else {
            sql = "未查询到符合条件的模板";
            logger.info(sql);
        }
        return sql;
    }


    public  String printFileContent(Object obj) throws IOException {
        StringBuffer sb = new StringBuffer();
       /* if (null == obj) {
            logger.error("参数为空");
            throw new RuntimeException("参数为空");
        }
        BufferedReader reader = null;
        // 如果是文件路径
        if (obj instanceof String) {
            reader = new BufferedReader(new FileReader(new File((String) obj)));
            // 如果是文件输入流
        } else if (obj instanceof InputStream) {
            reader = new BufferedReader(new InputStreamReader((InputStream) obj));
        }
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line+"\n");
        }
        reader.close();*/
        return sb.toString();
    }


}
